<%--
  Created by IntelliJ IDEA.
  User: leixiaolong
  Date: 2018/9/20
  Time: 下午5:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/include.jsp" %>

<html>
<head>
    <title>采购单新增</title>
    <link rel="stylesheet" href="/static/css/rpt-condition.css" media="all" type="text/css">

    <style>
        .layui-form-label {
            width: 160px !important;
        }
    </style>

    <style>
        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
        .layui-table-cell {
            overflow: visible !important;
        }

        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select {
            /*margin-top: -10px;*/
            /*margin-left: -15px;*/
            /*margin-right: -15px;*/
            /*solid: #d2d2d2;*/
            /*border: 1px;*/
        }

        /* 设置下拉框的高度与表格单元相同 */
        .layui-input, .layui-select, .layui-textarea {
            height: 30px !important;
        }
    </style>

    <style>
        .col-select-lg {
            margin-top: 10px;
            height: 30px;
            width: 300px;
            min-width: 200px;
            max-width: 600px;
        }

        .layui-input-inline {
            min-width: 300px;
            max-width: 600px;
        }
    </style>
</head>
<body class="layui-bg-gray">
<div class="layui-row layui-col-space10" style="margin: 10px; background-color: white">
    <div class="layui-container">
        <div class="layui-row layui-form">
            <div class="layui-col-md6 ">
                <div class="layui-form-item">
                    <label class="layui-form-label ">供货商名称：</label>
                    <div class="layui-input-inline">
                        <select id="supp_name" class="layui-form-select  col-select-lg">
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">采购类型：</label>
                    <div class="layui-input-inline">
                        <select id="purc_type" class="col-select-lg">
                            <option value="1" selected>现采</option>
                            <option value="2">赊购</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">收货仓库：</label>
                    <div class="layui-input-inline">
                        <select id="stor_code" class="layui-form-select col-select-lg">
                            <option value=1 selected>仓库1</option>
                            <option value=2>仓库2</option>
                        </select>
                    </div>
                </div>
            </div>
            <%--<div class="layui-col-md6">--%>
                <%--<div class="layui-form-item">--%>
                    <%--<label class="layui-form-label">源单据类型：</label>--%>
                    <%--<div class="layui-input-inline">--%>
                        <%--<select id="bill_type" class="layui-form-select col-select-lg">--%>
                            <%--<option value=1 selected>类型1</option>--%>
                            <%--<option value=2>类型2</option>--%>
                        <%--</select>--%>
                    <%--</div>--%>
                <%--</div>--%>
            <%--</div>--%>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">收货日期：</label>
                    <input id="deli_date" type="text" class="dom-add-input" style="text-align: center"
                           placeholder="yyyy-MM-dd">
                </div>
                <%--<input type="text" class="layui-input-inline dom-add-input">--%>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">源单据id：</label>
                    <input type="text" id="bill_id" class="layui-input-inline dom-add-input">
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">摘要：</label>
                    <input type="text" id="abstract" class="layui-input-inline dom-add-input">
                </div>
            </div>
        </div>
    </div>
</div>
<div style="margin: 10px; background-color: white;">
    <table class="layui-hide" id="tab_purc_cred_add" lay-filter="purc-add-filter"></table>
</div>

<div class="layui-btn-container" style="float: right; margin-right: 10%">
    <button class="layui-btn layui-btn-normal layui-btn-warm" lay-submit data-type="submit">提交</button>
    <button class="layui-btn layui-btn-normal layui-btn-warm" lay-submit data-type="cancel">取消</button>
</div>
</body>

<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-date.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/form-select.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/table-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/component/comm-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/tax-math.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-data.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/base-math.js"></script>
<script language='javascript' src="${pageContext.request.contextPath}/static/js/utils/moment.js"></script>

<script type="text/html" id="toolbarAdd">
    <div class="layui-btn-group" style="float: right; margin-right: 10px;">
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="add">新增</button>
        <%--<button class="layui-btn layui-btn-sm" lay-event="del">删除</button>--%>
    </div>
</script>

<script type="text/html" id="templateSelect">
    <select id='select_{{d.id}}' layui-filter="selectfish">
        <option value="" selected>请选择</option>
    </select>
</script>

<script type="text/html" id="templteOper">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="del">删除</button>
    </div>
</script>


<script>
    var recordNum = 0;
    var taxRate = 0;
    var gooddata = [];

    layui.use(["element", "form", "layer", "table", "jquery", "laydate"], function () {
        var element = layui.element, layer = layui.layer, table = layui.table, $ = layui.jquery;
        var form = layui.form, laydate = layui.laydate;

        //初始化商品信息数据
        loadGoodData();
        //初始化获取商品信息
        async function loadGoodData(){
            gooddata = await getGoodsInfo();
        }
        //初始化渲染组件
        renderDate('deli_date', moment().format('YYYY-MM-DD'));
        initSuppInfoSelect('supp_name');
        var paramSourcBillType = {
            sysCode: 21,
            code: 1
        }
        // initCodeTableSelect('bill_type', '/base/getSysCodeList', paramSourcBillType);
        var paramPurcType = {code: '1'};
        initCodeTableSelect('purc_type', '/base/getPurcTypeList', paramPurcType);
        initStorSelect('stor_code');

        table.set({
            limit: 50
        });
        var tableIns = table.render({
            id: 'tab_purc_cred_add',
            elem: '#tab_purc_cred_add',
            // toolbar: '#toolbarDemo',
            toolbar: '#toolbarAdd',
            defaultToolbar: [],
            cellMinWidth: 90,
            // even: true, //隔行背景
            height: 'full-300',
            cols: [[
                {field: 'id', title: '序号', align: 'center'},
                {field: 'goodCode', title: '商品编码', align: 'center', hide: true},
                {
                    field: 'goodName', title: '商品名称', minWidth: 140, templet: function (d) {
                        return loadGoodSelect(d.id, gooddata, d.goodCode);
                    }, align: 'center'
                },
                {field: 'varietyCode', title: '品种编码', align: 'center', hide: true},
                {field: 'varietyName', title: '品种名称', align: 'center', hide: true},
                {field: 'standardName', title: '商品规格', align: 'center'},
                {field: 'unit', title: '商品单位', align: 'center'},
                {
                    field: 'inTaxRate', title: '商品进项税率', align: 'center', templet: function (d) {
                        return getFloat(d.inTaxRate);
                    }
                },
                {
                    field: 'price', title: '商品价格', edit: true, align: 'center', templet: function (d) {
                        return getFloat(d.price);
                    }
                },
                {
                    field: 'noTaxPrice', title: '商品不含税价格', align: 'center', templet: function (d) {
                        return computeNoTaxPrice(d.price, d.inTaxRate);
                    }
                },
                {
                    field: 'amount', title: '商品数量', edit: true, align: 'center', templet: function (d) {
                        return getFloat(d.amount);
                    }
                },
                {
                    field: 'bal', title: '商品金额', align: 'center', templet: function (d) {
                        if (typeof(d.price) == 'undefined' || typeof(d.amount) == 'undefined') {
                            return 0;
                        }
                        return getFloat(d.price * d.amount);
                    }
                },
                {
                    field: 'noTaxBal', title: '商品不含税金额', align: 'center', templet: function (d) {
                        if (d.amount == null || d.amount.trim().length === 0) {
                            return 0;
                        }

                        return round((getFloat(d.price) - computeNoTaxPrice(d.price, d.inTaxRate)) * d.amount, 2);
                    }
                },
                {
                    field: 'estInTax', title: '预估进项税', align: 'center', templet: function (d) {
                        if (d.amount == null || d.amount.trim().length === 0) {
                            return 0;
                        }
                        return round((getFloat(d.price) - computeNoTaxPrice(d.price, d.inTaxRate)) * d.amount, 2);
                    }
                },
                {field: 'digest', title: '摘要', align: 'center', edit: true},
                {field: 'operator', title: '操作', fixed: 'right', templet: '#templteOper'}]],
            done: function () {
                console.log("渲染表格 over");
                form.render();
            },
            page: false
        });

        form.render('select');

        /**
         * 监控表头工具条事件
         */
        table.on('toolbar', function (obj) {
            switch (obj.event) {
                case 'add':
                    layer.msg('添加');
                    var newdata = table.cache["tab_purc_cred_add"];
                    if (newdata == null || newdata == 'undefined') {
                        newdata = [];
                    }

                    var newline = {};
                    newline['id'] = ++recordNum;

                    // newdata.unshift(newline);//左侧加入
                    newdata.push(newline);//右侧加入
                    table.reload('tab_purc_cred_add', {
                        data: newdata
                    });

                    loadGoodSelect(recordNum, gooddata);
                    form.render('select');
                    break;
                case 'del':
                    layer.msg('删除');
                    break;
                case 'update':
                    layer.msg('编辑');
                    break;
            }
        });

        /**
         * 监听表行工具bar事件
         */
        table.on('tool', function (obj) {
            //获得当前行数据
            var rowdata = obj.data;
            var layEvent = obj.event;//获得当前行事件
            var tr = obj.tr;//获得当前行tr的dom对象

            switch (layEvent) {
                case 'del':
                    layer.confirm("是否删除本条记录", {icon: 3}, function (index) {
                        obj.del();
                        layer.close(index);
                    });
                    break;
                default:
                    layer.msg("请等待功能开放");
                    break;
            }

            //同步更新缓存对应的值
            // obj.update({username:'123', title: 'xxx'});
        });

        /**
         * 监听编辑单元格事件
         */
        table.on('edit', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data;

            obj.update(data);
            form.render('select');
        });

        var active = {
            submit: function confirm() {
                var data = table.cache["tab_purc_cred_add"];
                var newdata = trimAllArray(data);

                var request = {
                    "suppCode": $('#supp_name').find('option:selected').val(),
                    "suppAbbrName": $('#supp_name').find('option:selected').text(),
                    // "contName": $('#cont_man').find('option:selected').text(),
                    // "contPhone": $('#cont_phone').val(),
                    "purcType": $('#purc_type').find('option:selected').val(),
                    "storCode": $('#stor_code').find('option:selected').val(),
                    "deliDate": $('#deli_date').val(),
                    // "sourBillType": $('#bill_type').find('option:selected').val(),
                    "sourBillId": $('#bill_id').val(),
                    "digest": $('#abstract').val(),
                    "credDetailData": newdata
                };
                var reqBody = (JSON.stringify(request));

                $.ajax({
                    type: "POST",
                    url: "/purc/cred/addPurcCred",
                    contentType: 'application/json',
                    dataType: 'json',//服务端返回数据类型
                    data: reqBody,
                    async: false,
                    success: function (data) {
                        if (data.rspCode == 'RSP000000') {
                            layer.msg("录入采购单成功,订单编号:" + data.data);
                            //刷新父页面table
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);

                            // parent.layui.table.reload("tab_cred", {});
                            parent.reloadTable();
                            return;
                        } else {
                            layer.msg("录入采购单失败:" + data.rspMsg);
                            return;
                        }
                    },
                    error: function (data) {
                        console.log("系统异常:" + data);
                        layer.msg("系统异常,请联系管理员");
                        return;
                    }
                });


            },
            cancel: function cancel() {
                layer.msg("关闭弹出订单录入");
                var parent_layer = parent.layer;
                var index = parent.layer.getFrameIndex(window.name); //获取当前窗体索引

                parent.layer.close(index);
                parent.layui.table.reload("tab_cred", {});
            }
        };

        form.on('submit', function (data) {
            var elem = data.elem;
            active[$(this).data("type")].call(this, elem);
        });

        /**
         * 监听select下拉框事件
         */
        form.on('select(sel-goods-filter)', async function (data) {
            //监听数据处理
            var goodCode = data.value;

            //获取当前行记录
            var rowData = await getRowItemById("tab_purc_cred_add", data.elem.id.substring(data.elem.id.indexOf("_") + 1, data.elem.id.length));

            //获取商品信息
            var goodInfo = await getGoodInfoById(goodCode);

            //获取税率
            if (taxRate == null || taxRate <= 0) {
                taxRate = getTaxRate();
            }
            //get商品信息 goodInfo
            var gooddata = {
                "id": rowData.id,
                "goodCode": data.value,
                "varietyCode": goodInfo.varietyCode,
                "inTaxRate": taxRate,
                "varietyName": goodInfo.varietyName,
                "standardName": goodInfo.standardName,
                "unit": goodInfo.unit,
                "inTaxRate": taxRate
            };

            var isClear = false;
            if (data.value == null || data.value.trim().length === 0) {
                var rowid = gooddata.id;
                gooddata = {};
                gooddata.id = rowid;
                isClear = true;
            }

            //对商品信息更新赋值
            updateRowItem("tab_purc_cred_add", gooddata, isClear);
        });
    });
</script>
</html>
